package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/*
 * @author zzr
 * @date: 2025/04/19  10:03
 * @description: TCP 回显服务器代码
 */
public class TcpEchoServer {

    private ServerSocket serverSocket = null;

    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动！");

        ExecutorService pool = Executors.newCachedThreadPool();
        while (true) {
            Socket clientSocket = serverSocket.accept();

//            Thread thread = new Thread(() -> {
//                processConnection(clientSocket);
//            });
//            thread.start();
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    processConnection(clientSocket);
                }
            });
        }
    }

    private void processConnection(Socket clientSocket) {
        System.out.printf("[%s:%d] 客户端上线！\n",clientSocket.getInetAddress(),clientSocket.getPort());

        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()) {

            Scanner scanner = new Scanner(inputStream);
            while (true) {
                // 读取完毕，客户端断开连接，就会产生读取完毕的提示信息
                if (!scanner.hasNext()) {
                    System.out.printf("[%s:%d] 客户下线！\n",clientSocket.getInetAddress(),clientSocket.getPort());
                    break;
                }
                // 1. 读取请求并解析。这里注意隐藏的约定，next 读的时候要读到空白字符才会结束
                // 因此就要求客户端发来的请求必须要带有空白符的结尾，比如 \n 或者 空格
                String request = scanner.next();

                // 2. 根据请求计算响应
                String response = process(request);

                // 3. 把响应返回给客户端
                // 用 PrintWriter 对 outputStream 进行一层包装~
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(request);
                printWriter.flush();

                System.out.printf("[%s:%d] request:%s, response:%s \n",clientSocket.getInetAddress(),clientSocket.getPort(),
                                  request,response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer = new TcpEchoServer(9090);
        tcpEchoServer.start();
    }
}
